package com.xzx.service;

import com.xzx.dto.CommonPage;
import com.xzx.mapper.RoleMapper;
import com.xzx.mapper.UserMapper;
import com.xzx.po.PermissionPO;
import com.xzx.po.RolePO;
import com.xzx.po.UserPO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/8/18 14:08
 */
@Slf4j
@Service
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionService permissionService;

    public CommonPage<RolePO> list(String query, int page, int size) {
        int count = roleMapper.count(query);
        int totalPage = count % size == 0 ? count / size : count / size + 1;
        List<RolePO> list = roleMapper.list(query, size, (page - 1) * size );
        CommonPage<RolePO> result = new CommonPage<>();
        result.setPage(page);
        result.setSize(size);
        result.setTotal(count);
        result.setTotalPage(totalPage);
        result.setData(list);
        result.setFirstPage(page == 1);
        result.setLastPage(page == totalPage);
        log.info("======result:{}", result);
        return result;
    }

    public void doAdd(RolePO rolePO) {
        roleMapper.insert(rolePO);
    }

    public void delete(List<Long> ids) {
        log.info("======ids:{}", ids);
        roleMapper.delete(ids);
        permissionService.deleteByRoleIds(ids);
    }

    public RolePO getById(Long id) {
        return roleMapper.getById(id);
    }

    public void doEdit(RolePO rolePO) {
        roleMapper.update(rolePO);
    }

    public List<RolePO> selectAll() {
        return roleMapper.selectAll();
    }

    public List<RolePO> selectByUserId(Long userId) {
        return roleMapper.selectByUserId(userId);
    }

    public void doAssign(Integer userId, List<Long> roleIds) {
        roleMapper.doAssign(userId, roleIds);
    }

    public void doUnassign(Integer userId, List<Long> roleIds) {
        roleMapper.doUnassign(userId, roleIds);
    }

    public List<PermissionPO> selectAllPermission(Long roleId) {
        return permissionService.treeByRoleId(roleId);
    }

    public void doAssignPermission(Long roleId, List<Long> permissionIds) {
        permissionService.doAssign(roleId, permissionIds);
    }

    public void deleteByUserId(List<Integer> userIds) {
        roleMapper.deleteByUserId(userIds);
    }


    public void selectPermissionByUserId(Long id) {

    }
}
